package com.illtamer.infinite.sillage.service.impl;

import com.illtamer.infinite.sillage.mapper.UserMapper;
import com.illtamer.infinite.sillage.pojo.SillageUserDetails;
import com.illtamer.infinite.sillage.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource(name = "userMapper")
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User user = userMapper.selectByUsername(username);
        if (user == null)
            throw new UsernameNotFoundException("Can not find user: " + username);
        return new SillageUserDetails(
                user.getUsername(),
                user.getPassword(),
                verifyAuthority(user),
                user
        );
    }

    /**
     * 获取用户权限
     * */
    private static Collection<? extends GrantedAuthority> verifyAuthority(User user) {
        return AuthorityUtils.createAuthorityList(
                user.getType() == 0 ? "ROLE_ADMIN" : "ROLE_VISITOR"
        );
    }

}
